<?php 
namespace frontend\controllers;
use yii\web\Controller;
use frontend\models\User;
use yii;
class LoginController extends Controller{
	public $layout='Other';
	/*
	用户登录
	 */
	public function actionIndex(){
		$request = YII::$app->request;
		$model = new User();

		if($request->isGET){

			return $this->render("index",['model'=>$model]);
		}
		if($request->isPOST){
			$data = $request->post('User');
			$sql = "select * from recruit_user where username='".$data['username']."' and password='".$data['password']."'";
			
			if($res =User::findBySql($sql)->asArray()->one()){
		
				   $cookies = Yii::$app->response->cookies;
					$cookies->add(new \yii\web\Cookie([
					    'name' => 'user',
					    'value' => serialize(array('username'=>$res['username'],'user_id'=>$res['id'])),
					]));

				
			        $user_ip = yii::$app->request->userIP;

			        $data['last_ip']=$user_ip;
			        $data['last_time']=time();;
			        $res = User::updateAll($data,['id'=>$res['id']]);
				
				return $this->redirect('?r=site/index');
			}else{
				 
				return $this->redirect('?r=login/index');
			}

		}
		
	}
	/*
	用户注册
	 */

	public function actionReg(){
		$request = YII::$app->request;
		$model = new User();

		if($request->isGET){
			return $this->render('signup',['model'=>$model]);
		}

		if($request->isPOST){

			$data = $request->post();
			$user_ip = $request->userIP;
			$model->creat_time = time();
			$model->creat_ip = $user_ip;
			if($model->load($data)&&$model->validate()){
				$res = $model->save();
				$id = $model->attributes['id'];
				if($res){
				    $cookies = Yii::$app->response->cookies;
					$cookies->add(new \yii\web\Cookie([
					    'name' => 'user',
					    'value' => serialize(array('username'=>$data['User']['username'],'user_id'=>$id)),
					]));
				  
				} 
				return $this->redirect('?r=site/index');
			}else{
		
				return $this->redirect('?r=login/reg');
			}
		}
	}
	/*
	退出登录
	 */
	public function actionLoginout(){
		$cookies = Yii::$app->response->cookies;
		$cookies->remove('user');
		return $this->redirect('?r=site/index');
	}

}
 ?>